<template>
  <div class="inventory">
    <a-card size="small">
      <c-table
        :data="tableData"
        :columns="columns"
        :showHeader="false"
        :reload="false"
        size="small"
      >
        <template v-slot:warehouse="{ row }">
          <span>{{ row.shortName }}</span>
        </template>
        <template v-slot:num>
          <span>1</span>
        </template>
      </c-table>
      <div slot="title" class="title">
        <span>实物库存明细</span>
        <span class="detail">
          <span>可关联数：{{ relationAble }}</span>
          <span>已关联数：{{ related }}</span>
          <span>允许超量：{{ orderData.overAmount }}</span>
        </span>
      </div>
      <c-button
        slot="extra"
        type="primary"
        @click="openModal"
        v-if="
          ((!isSeller() &&
            ($verifyBtn('buyerPricingRelationInventory') ||
              $verifyBtn('buyerConfirmRelationInventory'))) ||
            (isSeller() &&
              ($verifyBtn('sellerPricingRelationInventory') ||
                $verifyBtn('sellerConfirmRelationInventory')))) &&
            orderData.orderStatus ===
              orderDict.pricingStatus.waitContract.value &&
            !isLine()
        "
        >关联实物库存</c-button
      >
    </a-card>
    <c-modal
      v-model="visible"
      title="关联实物库存"
      :width="900"
      centered
      :okLoading="relationInventoryLoading"
      @ok="relationInventory"
      @cancel="searchKey = undefined"
      destroyOnClose
    >
      <a-input-search
        v-model="searchKey"
        @search="getAbleInventoryList"
        style="width: 400px;margin-bottom: 16px;"
        placeholder="可输入库存单号、库位号、材料号、备注进行搜索"
      ></a-input-search>
      <c-desc :data="orderData" :columns="descColumns" :column="1">
        <template v-slot:product>
          <span>{{ orderData.categoryName }}</span>
          <a-divider type="vertical" />
          <span>{{ orderData.brand }} </span>
          <span>{{ orderData.spec }} </span>
          <span>{{ orderData.material }} </span>
        </template>
        <template v-slot:warehouse>
          <span>{{ orderData.warehouse.shortName }}</span>
        </template>
      </c-desc>
      <p>
        <span>已选 {{ this.selectedIDs.length }} 个</span>
        <a-divider type="vertical" />
        <span class="detail">
          <span>可关联数：{{ relationAbleModal }}</span>
          <span style="padding-left: 26px;">已关联数：{{ relatedModal }}</span>
          <span style="padding-left: 26px;"
            >允许超量：{{ orderData.overAmount }}</span
          >
        </span>
      </p>
      <c-table
        :data="modalTableData"
        :columns="modalColumns"
        rowKey="id"
        :scroll="{ y: 500 }"
        selection
        :selectedRowKeys="selectedIDs"
        :getCheckboxProps="getCheckboxProps"
        noSelectAll
        @onSelectChange="onSelectChange"
        :showHeader="false"
        size="small"
      >
      </c-table>
    </c-modal>
  </div>
</template>

<script>
import {
  getrelatedentityinventorylist,
  getentityinventorylist
} from "@/api/inventory";
import {
  providerrelationinventorytoslideorder,
  providerrelationinventorytoconfirmorder,
  customerrelationinventorytoslideorder,
  customerrelationinventorytoconfirmorder
} from "@/api/order/inventory";
import orderDict from "@/dict/order";
import quotationDict from "@/dict/quotation";
import { isSeller, isLine } from "@/util/common";

const columns = [
  {
    title: "库存单号",
    dataIndex: "entityInventoryCode"
  },
  {
    title: "商品品种",
    dataIndex: "categoryName"
  },
  {
    title: "品牌",
    dataIndex: "brand"
  },
  {
    title: "规格",
    dataIndex: "spec"
  },
  {
    title: "材质",
    dataIndex: "material"
  },
  {
    title: "其他",
    dataIndex: "other"
  },
  {
    title: "仓库简称",
    dataIndex: "warehouse",
    scopedSlots: { customRender: "warehouse" }
  },
  {
    title: "库位号",
    dataIndex: "positionCode"
  },
  {
    title: "材料号/捆绑号",
    dataIndex: "materialCode"
  },
  {
    title: "件数",
    dataIndex: "num",
    scopedSlots: { customRender: "num" }
  },
  {
    title: "实物重量",
    dataIndex: "weight"
  },
  {
    title: "备注",
    dataIndex: "remark"
  }
];

const descColumns = [
  {
    label: "商品名称",
    slot: "product"
  },
  {
    label: "仓库简称",
    slot: "warehouse"
  }
];

const modalColumns = [
  {
    title: "库存单号",
    dataIndex: "entityInventoryCode"
  },
  {
    title: "库位号",
    dataIndex: "positionCode"
  },
  {
    title: "材料号",
    dataIndex: "materialCode"
  },
  {
    title: "实重",
    dataIndex: "weight",
    width: 100
  },
  {
    title: "备注",
    dataIndex: "remark"
  }
];

export default {
  props: {
    // 订单信息
    orderData: {
      type: Object
    }
  },
  data() {
    return {
      orderDict,
      tableData: [],
      columns,
      visible: false,
      descColumns,
      searchKey: undefined,
      modalTableData: [],
      modalColumns,
      selectedIDs: [], // 已选中的实物库存
      relationInventoryLoading: false // 提交loading
    };
  },
  computed: {
    // 已关联数
    related() {
      let res = 0;
      this.tableData.forEach(item => {
        res = this.$tools.formatFloat(res + item.weight);
      });
      return this.$tools.formatFloat(res);
    },
    // 可关联数
    relationAble() {
      let res;
      res = this.$tools.formatFloat(
        Number(this.orderData.dealAmount) +
          Number(this.orderData.overAmount) -
          this.related
      );
      return res;
    },
    // 已关联数 弹窗
    relatedModal() {
      let res = 0;
      this.modalTableData.forEach(item => {
        if (this.selectedIDs.indexOf(item.id) !== -1)
          res = this.$tools.formatFloat(res + item.weight);
      });
      return this.$tools.formatFloat(res);
    },
    // 可关联数 弹窗
    relationAbleModal() {
      let res;
      res = this.$tools.formatFloat(
        Number(this.orderData.dealAmount) +
          Number(this.orderData.overAmount) -
          this.relatedModal
      );
      return res;
    },
    // 判断能否勾选
    getCheckboxProps() {
      return record => {
        return {
          props: {
            // 重量大于可关联数，且不是已勾选的状态，则禁用
            disabled:
              record.weight > this.relationAbleModal &&
              this.selectedIDs.indexOf(record.id) === -1
          }
        };
      };
    }
  },
  methods: {
    isLine,
    isSeller,
    // 关联实物库存
    relationInventory() {
      // // 根据选中的实物库存id，查出对应的version，传参需带上
      // let entityInventoryDetails = [];
      // for (let i = 0; i < this.selectedIDs.length; i++) {
      //   for (let j = 0; j < this.modalTableData.length; j++) {
      //     if (this.selectedIDs[i].id === this.modalTableData[j].id) {
      //       entityInventoryDetails.push({
      //         entityInventoryId: this.modalTableData[j].id,
      //         version: this.modalTableData[j].version
      //       });
      //     }
      //   }
      // }
      let request = isSeller()
        ? this.orderData.priceType === quotationDict.priceType.pricing.value
          ? providerrelationinventorytoslideorder
          : providerrelationinventorytoconfirmorder
        : this.orderData.priceType === quotationDict.priceType.pricing.value
        ? customerrelationinventorytoslideorder
        : customerrelationinventorytoconfirmorder;
      this.relationInventoryLoading = true;
      request({
        orderId: this.orderData.id,
        version: this.orderData.version,
        entityInventoryIds: this.selectedIDs
      })
        .then(res => {
          this.$message.success("操作成功");
          this.visible = false;
          // 更新已关联实物库存
          this.getInventoryList();
          this.$emit("relationSuccess", res);
        })
        .finally(() => {
          this.relationInventoryLoading = false;
        });
    },
    // 勾选实物库存时回调
    onSelectChange(selectedKeys) {
      this.selectedIDs = selectedKeys;
      // 重新赋值，用于触发getCheckboxProps重新判断能否勾选
      this.modalTableData = [...this.modalTableData];
    },
    // 打开实物库存弹窗
    openModal() {
      this.selectedIDs = this.tableData.map(i => i.id);
      this.visible = true;
      this.getAbleInventoryList();
    },
    // 获取可关联实物库存
    getAbleInventoryList() {
      getentityinventorylist({
        orderId: this.orderData.id,
        searchKey: this.searchKey
      }).then(res => {
        this.modalTableData = res;
      });
    },
    // 获取已关联实物库存
    getInventoryList() {
      getrelatedentityinventorylist({
        orderId: this.orderData.id
      }).then(res => {
        this.tableData = res;
        this.$emit("relevanceInventory", this.tableData);
        this.selectedIDs = this.tableData.map(i => i.id);
      });
    }
  },
  created() {
    if (this.isLine()) {
      this.tableData = this.orderData.entityInventoryList;
      this.$emit("relevanceInventory", this.tableData);
    } else {
      this.getInventoryList();
    }
  }
};
</script>

<style lang="scss" scoped>
.title .detail {
  font-size: 14px;
  font-weight: normal;
  span {
    padding-left: 26px;
  }
}
</style>
